package com.example.secondhandmall.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

//import com.bumptech.glide.Glide;
import com.example.secondhandmall.MainActivity;
import com.example.secondhandmall.R;
import com.example.secondhandmall.api.Api;
import com.example.secondhandmall.api.ApiConfig;
import com.example.secondhandmall.api.MyCallback;
import com.example.secondhandmall.entity.LoginResponse;
import com.example.secondhandmall.util.RealPathFromUriUtils;
import com.example.secondhandmall.view.CircleTransform;
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ModifyInfoActivity extends BaseActivity {

    private EditText etName;
    private EditText etSign;
    private ImageView ivAvatar;
    private Button btnAvatar;
    private Button cancel;
    private Button modify;
    //    private HashMap info;
    private List<String> info;
    private String path = null;
    private String id;
    private String account;

    @Override
    protected int initLayout() {
        return R.layout.activity_modify_info;
    }

    @Override
    protected void initView() {
        etName = findViewById(R.id.et_name);
        etSign = findViewById(R.id.et_sign);
        ivAvatar = findViewById(R.id.iv_avatar);
        btnAvatar = findViewById(R.id.btn_avatar);
        cancel = findViewById(R.id.btn_cancel);
        modify = findViewById(R.id.btn_modify);
    }

    @Override
    protected void initData() {
//        info = (HashMap) getIntent().getSerializableExtra("info");
//        etName.setText((Integer) info.get("name"));
//        etSign.setText((Integer) info.get("sign"));
//        Picasso.with(this)
//                .load((Uri) info.get("avatar"))
//                .transform(new CircleTransform())
//                .into(ivAvatar);
        info = (List<String>) getIntent().getSerializableExtra("info");
        etName.setText(info.get(0));
        etSign.setText(info.get(1));
        Picasso.with(this)
                .load(info.get(2))
                .transform(new CircleTransform())
                .into(ivAvatar);
        id = info.get(3);
        account = info.get(4);

        ivAvatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addImg();
            }
        });
        btnAvatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addImg();
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        modify.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                modify();
            }
        });
    }

    private void addImg() {
        //动态申请权限
        ActivityCompat.requestPermissions(ModifyInfoActivity.this,
                new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                1);

        Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
        galleryIntent.addCategory(Intent.CATEGORY_OPENABLE);
        galleryIntent.setType("image/*");
        startActivityForResult(galleryIntent, 2);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 2) {
            if (null != data) {
                Uri uri = data.getData();
                ShowPhoto2(uri);
//                img_select = true;可以不选择图片，不选择就是不修改（还是要选择，不然怎么上传（还是可以不用，试了不传参也行））
                //但要判断，可以不用这个判断，path初始为空，没选择就是空，判断path为空就不传参
            }
        }
    }

    private void ShowPhoto2(Uri uri) {
        ContentResolver cr = getContentResolver();
        try {
            Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
//            ivAvatar.setImageBitmap(bitmap);
            Picasso.with(this)
                    .load(uri)
                    .transform(new CircleTransform())
                    .into(ivAvatar);
            path = RealPathFromUriUtils.getRealPathFromUri(this, uri);
            System.out.println(path);
        } catch (FileNotFoundException e) {
            Log.e("Exception", e.getMessage(), e);
        }
    }

    private void modify() {
        //换了头像
        if (path != null) {
            File file = new File(path);
//        String account = getStringFromSp("account");

            OkHttpClient httpClient = new OkHttpClient();
            MediaType mediaType = MediaType.parse("application/octet-stream");//设置类型，类型为八位字节流
            RequestBody requestBody = RequestBody.create(mediaType, file);//把文件与类型放入请求体

            MultipartBody multipartBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("file", file.getName(), requestBody)//文件名
                    .addFormDataPart("id", id)
                    .addFormDataPart("userId", account)
                    .addFormDataPart("userName", etName.getText().toString())
                    .addFormDataPart("userSignature", etSign.getText().toString())
                    .build();
            Request request = new Request.Builder()
                    .url(ApiConfig.BASE_URl + ApiConfig.USER_INFO)
                    .put(multipartBody)
                    .build();
            Call call = httpClient.newCall(request);
            call.enqueue(new Callback() {

                @Override
                public void onFailure(Call call, IOException e) {
                    System.out.println(e);
                    showToastSync("修改失败！");
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    //在这里根据返回内容执行具体的操作
                    final String res = response.body().string();
                    System.out.println(res);

                    //把json字符串转转换为实体对象
                    Gson gson = new Gson();
                    LoginResponse modifyInfoResponse = gson.fromJson(res, LoginResponse.class);
                    if (response.code() == 200 && modifyInfoResponse.isData()) {
                        finish();
                        showToastSync("修改成功！");
                    } else {
                        showToastSync("修改失败！");
                    }
                }
            });
        }

        //没改头像
        else {
//            File file = new File(path);
//        String account = getStringFromSp("account");

            OkHttpClient httpClient = new OkHttpClient();
            MediaType mediaType = MediaType.parse("application/octet-stream");//设置类型，类型为八位字节流
//            RequestBody requestBody = RequestBody.create(mediaType, file);//把文件与类型放入请求体

            MultipartBody multipartBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
//                    .addFormDataPart("file", file.getName(), requestBody)//文件名
                    .addFormDataPart("id", id)
                    .addFormDataPart("userId", account)
                    .addFormDataPart("userName", etName.getText().toString())
                    .addFormDataPart("userSignature", etSign.getText().toString())
                    .build();
            Request request = new Request.Builder()
                    .url(ApiConfig.BASE_URl + ApiConfig.USER_INFO)
                    .put(multipartBody)
                    .build();
            Call call = httpClient.newCall(request);
            call.enqueue(new Callback() {

                @Override
                public void onFailure(Call call, IOException e) {
                    System.out.println(e);
                    showToastSync("修改失败！");
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    //在这里根据返回内容执行具体的操作
                    final String res = response.body().string();
                    System.out.println(res);

                    //把json字符串转转换为实体对象
                    Gson gson = new Gson();
                    LoginResponse modifyInfoResponse = gson.fromJson(res, LoginResponse.class);
                    if (response.code() == 200 && modifyInfoResponse.isData()) {
                        finish();
                        showToastSync("修改成功！");
                    } else {
                        showToastSync("修改失败！");
                    }
                }
            });
        }
    }
}